package com.houdoudou.supplier.common;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UpLoadPic {

	   public static Map<String, Object> uploadFile(String uploadFile,String newName)
	    {
	      String end ="\r\n";
	      String twoHyphens ="--";
	      String boundary ="*****";
	      Map<String, Object> result_map= new HashMap<String, Object>();
	      try
	      {
	        URL url =new URL(Constant.BaseUrl+Constant.UploadUrl);
	        HttpURLConnection con=(HttpURLConnection)url.openConnection();
	        /* 允许Input、Output，不使用Cache */
	        con.setDoInput(true);
	        con.setDoOutput(true);
	        con.setUseCaches(false);
	        /* 设置传送的method=POST */
	        con.setRequestMethod("POST");
	        /* setRequestProperty */
	        con.setRequestProperty("Connection", "Keep-Alive");
	        con.setRequestProperty("Charset", "UTF-8");
	        con.setRequestProperty("Content-Type",
	                           "multipart/form-data;boundary="+boundary);
	       
	        /* 设置DataOutputStream */
	        DataOutputStream ds =
	          new DataOutputStream(con.getOutputStream());
	        ds.writeBytes(twoHyphens + boundary + end);
	        ds.writeBytes("Content-Disposition: form-data; "+
	                      "name=\"file1\";filename=\""+
	                      newName +"\""+ end);
	        ds.writeBytes(end);  
	        /* 取得文件的FileInputStream */
	        FileInputStream fStream =new FileInputStream(uploadFile);
	        /* 设置每次写入1024bytes */
	        int bufferSize =1024;
	        byte[] buffer =new byte[bufferSize];
	        int length =-1;
	        /* 从文件读取数据至缓冲区 */
	        while((length = fStream.read(buffer)) !=-1)
	        {
	          /* 将资料写入DataOutputStream中 */
	          ds.write(buffer, 0, length);
	        }
	        ds.writeBytes(end);
	     //   ds.writeBytes(twoHyphens + boundary + twoHyphens + end); // 这是一条结束符，我还要加一个分区，所以不能这么写，要下下面的分区符。
	  
	        //   ds.writeBytes(twoHyphens + boundary+ end);  //分区符
	        
	        /////一下由我添加，传输更多的文字数据，
	      
	        /*   String key="Supplier_Telnum";
	        String value="供应商电话--15520521958";
	    
	       
	        StringBuffer contentBody = new StringBuffer("--" +boundary); 
	        contentBody.append("\r\n")  
	        
	        .append("Content-Disposition: form-data; name=\"")  

	        .append(key + "\"")  

	        .append("\r\n")  

	        .append("\r\n")  

	        .append(value)  

	       .append("\r\n");  

	     //   .append("--")  

	     //   .append(boundary);  
	        String boundaryMessage1 = contentBody.toString();  
	        
	        ds.write(boundaryMessage1.getBytes("utf-8")); 
	        */
	        String endBoundary=twoHyphens + boundary + twoHyphens + end;
	        ds.write(endBoundary.getBytes("utf-8"));        
	        /////////////////
	        /* close streams */
	        fStream.close();
	        ds.flush();
	        /* 取得Response内容 */
	        
	       
	       
	        InputStream is = con.getInputStream();
	        int ch;
	        StringBuffer b =new StringBuffer();
	        int timecount=0;
	        while(timecount<1024*1024){
	        	timecount++;
	        while( ( ch = is.read() ) !=-1 )
	        {
	          b.append( (char)ch );
	        }
	        }
	        /* 将Response显示于Dialog */
	     //  showDialog("上传成功"+b.toString().trim());
	      //  result=new String(b.toString().toString().getBytes(),"UTF-8");
	        /* 关闭DataOutputStream */	    
	        System.out.println( "ResponseCode="+con.getResponseCode());
	        if(con.getResponseCode()==200){
	                        String backFromSevice=b.toString();
	                        
	                        System.out.println( "backFromSevice="+ backFromSevice);
	         		        result_map.put("ErrorInfo", backFromSevice);
	                                        
	        }else{
	        	result_map.put("ActionStatus", false);
				result_map.put("ErrorInfo", "图片上传失败");
	        }
	        ds.close();
	      
	        
	        con.disconnect();
	      }
	      catch(Exception e)
	      {
	    //    showDialog("上传失败"+e);
	    	  e.printStackTrace();
	      }
	      
	      return result_map;
	    }
	
	   public static Map<String, Object> uploadManyFiles(List<String> uploadFiles,List<String> newNames)
	    {
	      String end ="\r\n";
	      String twoHyphens ="--";
	      String boundary ="*****";
	      Map<String, Object> result_map= new HashMap<String, Object>();
	      try
	      {
	        URL url =new URL(Constant.BaseUrl+Constant.UploadUrl);
	        HttpURLConnection con=(HttpURLConnection)url.openConnection();
	        /* 允许Input、Output，不使用Cache */
	        con.setDoInput(true);
	        con.setDoOutput(true);
	        con.setUseCaches(false);
	        /* 设置传送的method=POST */
	        con.setRequestMethod("POST");
	        /* setRequestProperty */
	        con.setRequestProperty("Connection", "Keep-Alive");
	        con.setRequestProperty("Charset", "UTF-8");
	        con.setRequestProperty("Content-Type",
	                           "multipart/form-data;boundary="+boundary);
	        DataOutputStream ds =
	  	          new DataOutputStream(con.getOutputStream());
	        
	        for(int k=0 ;k<uploadFiles.size();k++){
	        /* 设置DataOutputStream */
	       System.out.println(newNames.get(k)+"          "+uploadFiles.get(k));
	        ds.writeBytes(twoHyphens + boundary + end);
	        ds.writeBytes("Content-Disposition: form-data; "+
	                      "name=\"file1\";filename=\""+
	                      newNames.get(k) +"\""+ end);
	        ds.writeBytes(end);  
	        /* 取得文件的FileInputStream */
	        FileInputStream fStream =new FileInputStream(uploadFiles.get(k));
	        /* 设置每次写入1024bytes */
	        int bufferSize =1024;
	        byte[] buffer =new byte[bufferSize];
	        int length =-1;
	        /* 从文件读取数据至缓冲区 */
	        while((length = fStream.read(buffer)) !=-1)
	        {
	          /* 将资料写入DataOutputStream中 */
	          ds.write(buffer, 0, length);
	        }
	        ds.writeBytes(end);
	        /* close streams */
	        fStream.close();
	        }
	     //   ds.writeBytes(twoHyphens + boundary + twoHyphens + end); // 这是一条结束符，我还要加一个分区，所以不能这么写，要下下面的分区符。
	  
	        //   ds.writeBytes(twoHyphens + boundary+ end);  //分区符
	        
	        /////一下由我添加，传输更多的文字数据，
	      
	        /*   String key="Supplier_Telnum";
	        String value="供应商电话--15520521958";
	    
	       
	        StringBuffer contentBody = new StringBuffer("--" +boundary); 
	        contentBody.append("\r\n")  
	        
	        .append("Content-Disposition: form-data; name=\"")  

	        .append(key + "\"")  

	        .append("\r\n")  

	        .append("\r\n")  

	        .append(value)  

	       .append("\r\n");  

	     //   .append("--")  

	     //   .append(boundary);  
	        String boundaryMessage1 = contentBody.toString();  
	        
	        ds.write(boundaryMessage1.getBytes("utf-8")); 
	        */
	        String endBoundary=twoHyphens + boundary + twoHyphens + end;
	        ds.write(endBoundary.getBytes("utf-8"));        
	        /////////////////
	       
	        ds.flush();
	        /* 取得Response内容 */
	        
	       
	       
	        InputStream is = con.getInputStream();
	        int ch;
	        StringBuffer b =new StringBuffer();
	        int timecount=0;
	        while(timecount<1024*1024){
	        	timecount++;
	        while( ( ch = is.read() ) !=-1 )
	        {
	          b.append( (char)ch );
	        }
	        }
	        /* 将Response显示于Dialog */
	     //  showDialog("上传成功"+b.toString().trim());
	      //  result=new String(b.toString().toString().getBytes(),"UTF-8");
	        /* 关闭DataOutputStream */	    
	        System.out.println( "ResponseCode="+con.getResponseCode());
	        if(con.getResponseCode()==200){
	                        String backFromSevice=b.toString();
	                        System.out.println( "backFromSevice="+ backFromSevice);
	       
	                       if(backFromSevice.equals("OK")){
	                    	   result_map.put("ActionStatus", true);
	           				       result_map.put("ErrorInfo", "图片上传成功");
	                                            }else{
	                    	   result_map.put("ActionStatus", false);
	           				       result_map.put("ErrorInfo", backFromSevice);
	                                            }
	        }else{
	        	result_map.put("ActionStatus", false);
				result_map.put("ErrorInfo", "图片上传失败");
	        }
	        ds.close();
	      
	        
	        con.disconnect();
	      }
	      catch(Exception e)
	      {
	    //    showDialog("上传失败"+e);
	    	  e.printStackTrace();
	      }
	      
	      return result_map;
	    }
	
}
